package com.chuanzhi.recyclingmalladmin.service.imp;

import cn.hutool.http.server.HttpServerResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuanzhi.recyclingmall.common.result.Result;
import com.chuanzhi.recyclingmall.common.result.ResultCode;
import com.chuanzhi.recyclingmall.common.utils.IdentifyCode;
import com.chuanzhi.recyclingmall.common.utils.JwtUtil;
import com.chuanzhi.recyclingmalladmin.mapper.UserMapper;
import com.chuanzhi.recyclingmalladmin.po.LoginUser;
import com.chuanzhi.recyclingmalladmin.po.User;
import com.chuanzhi.recyclingmalladmin.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * @author gong
 * @date 2023/11/30
 */
@Service
public class UserLoginServiceImp extends ServiceImpl<UserMapper,User> implements UserLoginService {


    /**
     *
     *///讲token存入redis中
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AuthenticationManager authenticationManager;



    /**
     * @param user
     * @return {@link Result}
     */
    @Override
    public Result getUserLogin(User user) {
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户或密码错误");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(loginUser.getUser().getUsername());
        Map<String, String> data = new HashMap<>();
        data.put("token",jwt);
        redisTemplate.opsForValue().set(loginUser.getUser().getUsername()+"token",loginUser);
        return Result.instance(200,"登录成功",data);
    }

    /**
     * @return {@link Result}
     */
    @Override
    public Result userLogout() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        boolean deleteToken = redisTemplate.delete(loginUser.getUser().getUsername()+"token");
        if(deleteToken){
            return Result.failed(200,"欢迎下次回来");
        }else {
            return Result.failed(String.valueOf(ResultCode.BIZ_OTHER_ERROR));
        }
    }
    //生成验证码
    public static String generateCaptcha() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        return sb.toString();
    }

    @Override
    public Result addUserLogin(User user,String captcha) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = user.getPassword();
        user.setPassword(bCryptPasswordEncoder.encode(password));
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        User code = userMapper.selectOne(wrapper);
        String redisCaptha = (String) redisTemplate.opsForValue().get(uuid + "captcha");
        if (redisCaptha.equals(captcha)){
            if (!Objects.isNull(code)){
                return Result.failed(409,"该用户已存在");
            }else {
                int insert = userMapper.insert(user);
                if (insert>0){
                    return Result.failed(200,"注册成功");
                }else {
                    return Result.failed(String.valueOf(ResultCode.PROGRAM_INSIDE_EXCEPTION));
                }

            }
        }else {
            return Result.failed(401,"验证码错误");
        }

    }

    static UUID uuid = UUID.randomUUID();

//    @Override
//    public Result getCaptcha() {
//        redisTemplate.delete(uuid+"captcha");
//        String captcha = generateCaptcha();
//        redisTemplate.opsForValue().set(uuid+"captcha",captcha,1,TimeUnit.DAYS);
//        HashMap<String, String> data = new HashMap<>();
//        data.put("captcha",captcha);
//        return Result.success(data);
//    }
    @Override
    public void getCaptchaImags(String captcha) {
        redisTemplate.delete(uuid+"captcha");
        redisTemplate.opsForValue().set(uuid+"captcha",captcha,1,TimeUnit.DAYS);

    }



}
